﻿/*
 Copyright (c) 2012 Aaron Zhang
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

using System;
using System.Collections.Generic;

namespace SharkCrawler.Common
{
    public class UrlTree
    {
        private UrlTreeNode root = new UrlTreeNode();

        public UrlTree()
        {
            root.Depth = 0;
            root.Name = "www_root";
        }

        public bool Insert(string url)
        {
            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                UrlTreeNode node = new UrlTreeNode(url);
                return root.Insert(node);
            }
            else
            {
                return false;
            }
        }
    }

    public class UrlTreeNode
    {
        private string url;
        private string name;
        private string protocal;
        private string host;

        /// <summary>
        /// For internal use only, tracking full path of url.
        /// eg. pathes of http://www.microsoft.com/msdn/123 is
        /// com,microsoft,www,msdn,123
        /// </summary>
        private string[] pathes;
        
        /// <summary>
        /// Depth of the node, start from 0 = root node.
        /// </summary>
        private int depth;
        private List<UrlTreeNode> children = new List<UrlTreeNode>();

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int Depth
        {
            get { return depth; }
            set { depth = value; }
        }

        public string Url
        {
            get { return url; }
            set { Init(value); }
        }

        public UrlTreeNode()
        {
        }

        public UrlTreeNode(string url)
        {
            Init(url);
        }

        /// <summary>
        /// Inserts url node into the tree.
        /// </summary>
        /// <param name="insertNode">Node to be inserted</param>
        /// <returns>Whether the node is inserted successfully, 
        /// return false if url already exists.</returns>
        public bool Insert(UrlTreeNode insertNode)
        {
            bool inserted = false;
            bool foundRoot = false;
            foreach (UrlTreeNode child in children)
            {
                if (insertNode.pathes.Length > depth + 1)
                {
                    if (string.Compare(insertNode.pathes[depth], child.name, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        inserted = child.Insert(insertNode);
                        foundRoot = true;
                        break;
                    }
                }
                else if (insertNode.pathes.Length == depth + 1)
                {
                    if (string.Compare(insertNode.pathes[depth], child.name, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        if (string.IsNullOrEmpty(child.url))
                        {
                            child.url = insertNode.url;
                            child.pathes = insertNode.pathes;
                            child.protocal = insertNode.protocal;
                            child.host = insertNode.host;
                            inserted = true;
                        }
                        foundRoot = true;
                        break;
                    }
                }
            }

            if (!foundRoot)
            {
                if (insertNode.pathes.Length == depth + 1)
                {
                    insertNode.Name = insertNode.pathes[depth];
                    insertNode.Depth = depth + 1;
                    children.Add(insertNode);
                    inserted = true;
                }
                else if (insertNode.pathes.Length > depth + 1)
                {
                    UrlTreeNode child = new UrlTreeNode();
                    child.Name = insertNode.pathes[depth];
                    child.Depth = depth + 1;
                    children.Add(child);
                    inserted = child.Insert(insertNode);
                }
            }
            return inserted;
        }

        /// <summary>
        /// Initialize a node.
        /// </summary>
        /// <param name="url"></param>
        private void Init(string url)
        {
            this.url = url;
            string[] splitedUrl = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            protocal = splitedUrl[0];
            host = splitedUrl[1];
            name = splitedUrl[splitedUrl.Length - 1];
            string[] domains = host.Split('.');
            pathes = new string[splitedUrl.Length - 2 + domains.Length];

            int i = 0;
            for (int j = domains.Length - 1; j >= 0; j--, i++)
            {
                pathes[i] = domains[j];
            }
            for (int j = 2; j < splitedUrl.Length; j++, i++)
            {
                pathes[i] = splitedUrl[j];
            }
        }
    }
}
